#!/usr/bin/env python
# _*_ coding: utf-8 *_*
'''
Created on 29 janv. 2010
'''

import math
import wave        #http://docs.python.org/library/wave.html
import struct
import audioop     #http://docs.python.org/library/audioop.html


def make_soundfile(freq=440, data_size=10000, filename="sine_wave1.wav"):
    """
    create a synthetic 'sine wave' wave file with frequency freq
    file has a length of about data_size*2 and the given filename

    @author: vegaseat
    http://www.python-forum.org/pythonforum/viewtopic.php?f=2&t=10644
    """
    frate = 11025.0  # framerate as a float
    amp = 8000.0     # multiplier for amplitude

    # make a sine list ...
    sin_list = []
    for i in range(data_size):
        sin_list.append(math.sin(2*math.pi*freq*(i/frate)))
        
    wav_file = wave.open(filename, "w")

    # required parameters ... http://pyalsaaudio.sourceforge.net/terminology.html
    nchannels = 1            # Nombre de canaux => Mono
    sampwidth = 2            # Octets par echantillons : 16
    framerate = int(frate)   # Frequence echantillonnage
    nframes = data_size           # 1 Frame = ensemble des echantillons des canaux a un temps t 
    comptype = "NONE"            # Presence d'une Methode de compression 
    compname = "not compressed"  # Nom de cette methode

    # set all the parameters at once
    wav_file.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))

    # now write out the file
    print("may take a few seconds ...")
    for s in sin_list:
        # write the audio frames, make sure nframes is correct
        wav_file.writeframes(struct.pack('<h', s*amp/1.5))
        # La fonction pack permet de generer une string.
        # Avec le format h, il s agit d'une succession d'octets 
        # tq  "16 bits signes" (h) en little endian "<"
        # http://docs.python.org/library/struct.html
    wav_file.close()
    print( "%s written" % filename)

    
def process_soundfile(filenameorg="sine_wave1.wav"):
    
    signal = wave.open(filenameorg, 'rb' )
    
    Nframes = float(signal.getnframes())
    width = signal.getsampwidth()
    frameRate = signal.getframerate()
    
    frame = signal.readframes(1)
    power =[]
    while len(frame):
        power.append(frame) #audioop.rms(frame, width ))
        frame = signal.readframes(1)

    signal.close()
    
    #----------------------------------------------------------------
    # Process
    #----------------------------------------------------------------
   
    new_signal = wave.open(filenameorg+".new", 'wb')
    
    new_signal.setsampwidth(width)
    new_signal.setframerate(frameRate)
    new_signal.setnchannels(signal.getnchannels())

    for j in range(len(power)):
        data = power[j]
        new_signal.writeframes(data)
    
    new_signal.close() 


if __name__ == '__main__':
    freq = 440.0
    size = 40000  # data size
    filename = "WaveTest2.wav"
    make_soundfile(freq, size, filename)
    process_soundfile(filename)